package com.wuseguang.springcloud.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.jdbc.GuangXiZhuzongDockingLogJdbc;
import com.wuseguang.springcloud.dao.repository.GuangXiZhuzongDockingLogRepository;
import com.wuseguang.springcloud.dao.repository.ImportAndExportSchoolsRepository;
import com.wuseguang.springcloud.dao.repository.StudentRepository;
import com.wuseguang.springcloud.entity.GuangXiZhuzongDockingLog;
import com.wuseguang.springcloud.entity.ImportAndExportSchools;
import com.wuseguang.springcloud.entity.Student;
import com.wuseguang.springcloud.mina.changYing.*;
import com.wuseguang.springcloud.service.TheThirdPartyService;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.ListUtil;
import com.wuseguang.springcloud.util.Result;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import com.wuseguang.springcloud.util.byteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.*;

@Service
public class TheThirdPartyServiceImpl implements TheThirdPartyService {


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private GuangXiZhuzongDockingLogRepository guangXiZhuzongDockingLogRepository;

    @Autowired
    private GuangXiZhuzongDockingLogJdbc guangXiZhuzongDockingLogJdbc;
    @Autowired
    private ImportAndExportSchoolsRepository importAndExportSchoolsRepository;
    @Autowired
    private WXJdbc wXJdbc;
    @Autowired
    private StudentRepository studentRepository;

    @Override
    public String guangxiZhuzongDocking(String data) {

        logger.info("广西朱老板学生进去校信息对接   过来信息如下：{}",data);



       //广西朱老板的对接日志
        GuangXiZhuzongDockingLog log = new GuangXiZhuzongDockingLog();
        //接收时间
        log.setTime(new Date());
        //接收到的信息
        log.setRecordData(data);
        //闸机对接
        log.setType(0);

        guangXiZhuzongDockingLogRepository.save(log);

        logger.info("详情数据 ={}", data);

        //获取功能状态吗
        String function = data.substring(4, 6);
        //包号
        String packageNumber = data.substring(6, 10);


         if ("34".equals(function)) {
            //所有考勤数据
            String kahao = data.substring(30, data.length());

            //学生进出记录
            ImportAndExportSchools iaes = new ImportAndExportSchools();

             //获取物理卡号
             String physicsCardNumber = kahao.substring(16, 36);
             //获取进离校时间
             String time = kahao.substring(36, 50);
             //获取进离校状态0进1出
             String type = kahao.substring(50, 51);
             //获取逻辑卡号
             String logicCardNumber = kahao.substring(0, 8);
             //十六进制转10进制
             BigInteger bigint=new BigInteger(logicCardNumber.trim(), 16);
             String  numb=bigint.toString();
             //卡号长度9前面补0
             if(numb.length()==9){
                 numb="0"+numb;
             }
             System.err.println("16进制卡号："+bigint);
             System.err.println("卡号："+numb);
             //根据卡号查询学生信息
             Student student = studentRepository.findByCardNumber(numb.toString());
             if(student==null){
                 return "0011" + function + packageNumber + "0";
             }
            //添加进出记录
            iaes.setStudentId(student.getId());
            iaes.setType(Integer.valueOf(type));
            iaes.setTime(DateUtil.strToDateLong(time, "yyyyMMddHHmmss"));
            importAndExportSchoolsRepository.save(iaes);

             //小程序推送
             //appletPush(student,type);
             //公众号推送
             officialAccountPush( student, type);

            return "0011" + function + packageNumber + "1";

        } else if ("35".equals(function)) {

            //所有考勤数据
            String s = data.substring(30, data.length());

            List<String> dateList = ListUtil.getStrList(s,51);

            //循环每一张卡的信息
            for (String kahao:dateList) {
                //学生进出记录
                ImportAndExportSchools iaes = new ImportAndExportSchools();

                //获取物理卡号
                String physicsCardNumber = kahao.substring(16, 36);
                //获取进离校时间
                String time = kahao.substring(36, 50);
                //获取进离校状态0进1出
                String type = kahao.substring(50, 51);
                //获取逻辑卡号
                String logicCardNumber = kahao.substring(0, 8);
                //十六进制转10进制
                BigInteger bigint=new BigInteger(logicCardNumber.trim(), 16);
                String  numb=bigint.toString();
                //卡号长度9前面补0
                if(numb.length()==9){
                    numb="0"+numb;
                }
                System.err.println("16进制卡号："+logicCardNumber.trim());
                System.err.println("卡号："+numb);
                //根据卡号查询学生信息
                Student student = null;

                try {
                    student =   studentRepository.findByCardNumber(numb.toString());
                }catch (Exception e){
                    logger.info("学生错误");
                }

                if(student==null){
                   continue;
                }
                //添加进出记录
                iaes.setStudentId(student.getId());
                iaes.setType(Integer.valueOf(type));
                iaes.setTime(DateUtil.strToDateLong(time, "yyyyMMddHHmmss"));
                importAndExportSchoolsRepository.save(iaes);
                //小程序推送
                //appletPush(student,type);
                //公众号推送
                officialAccountPush( student, type);
            }
            return "0011" + function + packageNumber + "1";
        }else if("82".equals(function)){
             return "0011" + function + "9999"+DateUtil.dateToString(new Date(),"yyyyMMddHHmmss");
         }

        return "0011" + function + packageNumber + "1";

    }

    @Override
    public AiSendMsgDataModle guangxiZhuzongDocking53600(AiDataModel model) {


        try{
            //广西朱老板的对接日志
            GuangXiZhuzongDockingLog log = new GuangXiZhuzongDockingLog();
            //接收时间
            log.setTime(new Date());
            //接收到的信息
            log.setRecordData(new String(model.getData()));
            //闸机对接
            log.setType(1);



            AiSendMsgDataModle sendModle = new AiSendMsgDataModle();

            logger.info("广西朱老板学生进去校信息对接   过来信息如下：{}",model.toString());
            //获取指令
            char aChar = ByteArrayUtils_BE.getChar(model.getOrder());


            JSONObject json = new JSONObject();
            json.put("key","");
            json.put("val","");

            //判断是否是登录
            if (aChar == AiCameraToCloudConstants.LOGINORDER) {
                logger.info("是登陆");
                //获取指令

                json.put("service_anme",FaceServiceName.AI_LOGIN);
                sendModle.setType(0);
            }else if(aChar == AiCameraToCloudConstants.JSONORDER){

                log.setRecordData(log.getRecordData()+":mac地址:"+byteUtil.getMacString(model.getMac()).toUpperCase());

                guangXiZhuzongDockingLogRepository.save(log);
                logger.info("设备端上传数据");
                JSONObject josn =JSONObject.parseObject(new String(model.getData()));
                //获取指令

                sendModle.setType(2);
                //获取上传类型
                String serviceNme = josn.get("service_name").toString();
                logger.info("上传类型："+serviceNme);
                //判断是否为人脸上传如果不是都不理它
                if("HaPushFace".equals(serviceNme)){
                    json.put("service_anme",serviceNme);
                    logger.info("人脸打卡数据上传："+model.getData());
                    //获取mac地址的进出状态
                    String sql = "select CONCAT(school_id,'-',type) string from guangxi_mac_address where mac_address =?";
                    //获取mac设备进出状态
                    String type = guangXiZhuzongDockingLogJdbc.queryString(sql, byteUtil.getMacString(model.getMac()).toUpperCase());
                    //schoolAndType [0] 学校id
                    //schoolAndType [1] 进出状态
                    String [] schoolAndType = type.split("-");
                    //获取卡号
                    String logicCardNumber =josn.get("wiegand").toString().trim().length()==9 ?
                            "0"+josn.get("wiegand").toString():josn.get("wiegand").toString();
                    //如果
                    if(logicCardNumber.isEmpty()){
                        //返回信息
                        sendModle.setSendMsg(json.toString());
                        //创建随机数
                        Random random=new Random();
                        //创建随机数
                        sendModle.setRandId(random.nextInt(99999999));
                        return sendModle;
                    }
                    //获取时间
                    String time = josn.get("time").toString();
                    //学生进出记录
                    ImportAndExportSchools iaes = new ImportAndExportSchools();
                    //十六进制转10进制
                    //根据卡号查询学生信息
                    Student student = studentRepository.findByCardNumber(logicCardNumber);
                    logger.info("学生卡号："+logicCardNumber);
                    //学生不为空
                    if(student!=null){
                        logger.info("广西对接学生不为空");
                        //添加进出记录
                        iaes.setStudentId(student.getId());
                        iaes.setType(Integer.valueOf(schoolAndType[1]));
                        iaes.setTime(DateUtil.strToDateLong(DateUtil.stampToDate(time),"yyyy-MM-dd HH:mm:ss"));
                        importAndExportSchoolsRepository.save(iaes);

                        //小程序推送
                        //appletPush(student,type);
                        //公众号推送
                        officialAccountPush( student, schoolAndType[1]);
                    }

                }


            }else if(aChar == AiCameraToCloudConstants.HEARTORDER){
                logger.info("心跳指令");
                sendModle.setType(1);
                json.put("service_anme",FaceServiceName.AI_HEART);
            }

            //返回信息
            sendModle.setSendMsg(json.toString());
            //创建随机数
            Random random=new Random();
            //创建随机数
            sendModle.setRandId(random.nextInt(99999999));
            return sendModle;

        }catch (Exception e){
            logger.info("过来的数据有误不做处理");
            AiSendMsgDataModle sendModle = new AiSendMsgDataModle();
            //返回信息
            sendModle.setSendMsg("");
            sendModle.setType(0);
            //创建随机数
            Random random=new Random();
            //创建随机数
            sendModle.setRandId(random.nextInt(99999999));
            return sendModle;
        }


    }


    /**
     * 学生进离校小程序推送
     * @param student  学生信息
     * @param type 0进校，离校
     */
    public  void appletPush(Student student,String type){

        //获取token
        String accessToken = wXJdbc.getAccessToken(1);

        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";

        //家长openid
        Map<String,Object>  parent = guangXiZhuzongDockingLogJdbc.queryMap(sql, student.getId());

        String openId = (String) parent.get("open_id_one");

        sql = "select COUNT(1) count from user_subscription_template ust left JOIN we_chat_template wt " +
                "on(wt.id=ust.template_id) where wt.template_id='SgHgOWeECoiWY6tukJP1RDq1edrJT2bP-Z4UdIe0-c4' and ust.open_id =? and ust.state=0 ";
        //判断这个用户这个小程序是否订阅了
        int count = guangXiZhuzongDockingLogJdbc.queryCount(sql,openId);
        //判断openId是否为空
        if (!StringUtils.isEmpty(openId)&&count>0) {
            //查询学校名称
            sql = "select school_name string FROM school where id =?";
            //学校名称
            String schoolName = guangXiZhuzongDockingLogJdbc.queryString(sql, student.getSchoolId());

            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("name2", student.getStudentName());
            pushMap.put("phrase3", "0".equals(type) ? "进校" : "离校");
            pushMap.put("date4", DateUtil.getTimeAndMinutes());
            pushMap.put("thing5", schoolName);
            pushMap.put("thing9", student.getStudentName() + "同学" + ("0".equals(type) ? "进入学校" : "离开学校"));
            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送订阅消息
            WXUtil.sendWechatmsgToUser(accessToken, openId, "SgHgOWeECoiWY6tukJP1RDq1edrJT2bP-Z4UdIe0-c4", "", json, "trial", "");
            wXJdbc.updateSubscribe(openId,"SgHgOWeECoiWY6tukJP1RDq1edrJT2bP-Z4UdIe0-c4");
        }
    }


    /**
     * 学生进离校公众号推送
     * @param student  学生信息
     * @param type 0进校，离校
     */
    public void  officialAccountPush(Student student,String type){

        //获取token
        String accessToken = wXJdbc.getOfficialAccountAccessToken(0);

        //查询家长的小程序openId
        String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";

        //家长openid
        Map<String,Object>  parent = guangXiZhuzongDockingLogJdbc.queryMap(sql, student.getId());
        //获取公众号的openid
        String openId = (String) parent.get("open_id_two");
        //判断openid是否为空
        if (!StringUtils.isEmpty(openId)) {

            //查询班级名称
            sql = "select `name` string from classes where id = ?";
            String className = guangXiZhuzongDockingLogJdbc.queryString(sql,student.getClassId());


            Map<String, Object> pushMap = new HashMap<>();
            pushMap.put("first","家长您好，您的孩子有一条新的进出校信息。");
            pushMap.put("keyword1",student.getStudentName());
            pushMap.put("keyword2","0".equals(type) ? "进校" : "离校");
            pushMap.put("keyword3",DateUtil.getTimeAndMinutes());
            pushMap.put("remark","感谢您的支持。");

            //跳转小程序信息
            JSONObject appletJson= new JSONObject();
            appletJson.put("appid","wx30b606bac7775eba");
            appletJson.put("pagepath","pages/leavingSchool/checkStu?class_name="+className);

            //解析后的数据
            JSONObject json = TemplateTools.initializationData(pushMap);
            //推送公众号信息
            WXUtil.officialAccountPush(accessToken,openId,"Gm7b6gou5IEdsViu6CLxi46zHRvGUuuljQiVWlKbSZs","",appletJson,json);
        }
    }


    public Result  ceshi(){
        String l = "{\"service_name\":\"HaPushFace\",\"faceid\":-1,\"facename\":\"李发湖\",\"time\":1591004555759,\"img\":1308,\"inOutId\":1308,\"wiegand\":\"1234567890\"}";

        JSONObject josn =JSONObject.parseObject(l);



        String sql = "select CONCAT(school_id,'-',type) string from guangxi_mac_address where mac_address =?";
        //获取mac设备进出状态
        String type = guangXiZhuzongDockingLogJdbc.queryString(sql, "B6:4A:84:97:7D:71");
        //schoolAndType [0] 学校id
        //schoolAndType [1] 进出状态
        String [] schoolAndType = type.split("-");
        //获取卡号
        String logicCardNumber =(String) josn.get("wiegand");
        //获取时间
        String time = josn.get("time").toString();
        //学生进出记录
        ImportAndExportSchools iaes = new ImportAndExportSchools();

        //根据卡号查询学生信息
        Student student = studentRepository.findByCardNumber(logicCardNumber);
        logger.info("学生卡号："+logicCardNumber);
        //学生不为空
        if(student!=null){
            logger.info("广西对接学生不为空");
            //添加进出记录
            iaes.setStudentId(student.getId());
            iaes.setType(Integer.valueOf(schoolAndType[1]));
            iaes.setTime(DateUtil.strToDateLong(DateUtil.stampToDate(time),"yyyy-MM-dd HH:mm:ss"));
            importAndExportSchoolsRepository.save(iaes);

            //小程序推送
            //appletPush(student,type);
            //公众号推送
            officialAccountPush( student, schoolAndType[1]);
        }
        return new Result();
    }
}
